//
//  FovaLocationUtil.m
//  ICBCAbroadiPhoneBank
//
//  Created by KFZXZHUHAQ on 17/4/4.
//
//

#import "FovaLocationUtil.h"
#import <CoreFoundation/CoreFoundation.h>
@interface FovaLocationUtil ()
{
    GetLocationCallBack     _getLocationCallBack;
    GetLocationAddressCallBack     _getLocationAddressCallBack;
    NSTimer *_locaitonTimer;
    int _locationTime;
    
    NSTimer *_geoTimer;
    int _geoTime;
 
}

@end
@implementation FovaLocationUtil


+ (instancetype)getInstance {
    static FovaLocationUtil *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}



- (id)init
{
    if(self = [super init]){
      if (self.locationManager == nil) {
            // 定位管理器
            self.locationManager = [[CLLocationManager alloc] init];  // 创建位置管理器
            //if ([[ui d currentDevice].systemVersion>= 8.0) {
                //由于IOS8中定位的授权机制改变 需要进行手动授权
                [self.locationManager requestAlwaysAuthorization];
                [self.locationManager requestWhenInUseAuthorization];
       //    }
            self.locationManager.delegate = self;
        }
    }
    return self;
}

- (void)getLocationWithCallBack:(GetLocationCallBack)callBack
{
    if(callBack){
        _getLocationCallBack = [callBack copy];
    }

    [self.locationManager startUpdatingLocation];//开启定位
    
    _locaitonTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkLocationTime) userInfo:nil repeats:YES];


}
#pragma mark 定位成功以后-获取地理位置的,地理编码
- (void)getLocationAddressWithCallBack:(GetLocationAddressCallBack)callBack
{
    
    if(callBack){
        _getLocationAddressCallBack = [callBack copy];
    }
    
    [self getLocationWithCallBack:^(CLLocation *location, NSError *error) {
        if(location){
            
            _geoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkGeoTime) userInfo:nil repeats:YES];
            
            //地理编码
            if (self.geocoder == nil) {
                self.geocoder = [[CLGeocoder alloc] init];
            }
            [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                if(error || placemarks.count == 0){
                    CLPlacemark *placemark=[placemarks firstObject];
                    
                    NSLog(@"反geo检索失败 error = %@",error);
                    [self doLocationAddressCallBackWithLocation:nil andResult:error];
                }else{
                    CLPlacemark *placemark=[placemarks firstObject];
                    
                    NSLog(@"反geo检索成功");
                    NSError *error = nil;
                    [self doLocationAddressCallBackWithLocation:placemarks andResult:error];
                }
            }];
        }else{
            [self doLocationAddressCallBackWithLocation:nil andResult:error];
        }
    }];
    
}

- (void)checkLocationTime
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        return;
    }
    
    if(_locationTime++ >= 5){
        NSLog(@"locationTime>>>>>5");
      
    }else{
        NSLog(@"locationTime<<<<<5");
    }
}

- (void)checkGeoTime
{
    if(_geoTime++ >= 5){
        NSLog(@"GeoTime>>>>>5");
        [self.geocoder cancelGeocode];
        
    }else{
        NSLog(@"GeoTime<<<<<5");
    }
}

#pragma mark CLLocationManager 代理
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation* location = locations.lastObject;
    NSError *error = nil;
    [self doLocationCallBackWithLocation:location andResult:error];
    [manager stopUpdatingLocation];
}

//定位失败以后调用
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    NSLog(@"did failed with Error, erro code = %@", error);
    [self doLocationCallBackWithLocation:nil andResult:error];

}

- (void)doLocationCallBackWithLocation:(CLLocation *)location andResult:(NSError *)error
{

    if(_getLocationCallBack){
        _getLocationCallBack(location, error);
        _getLocationCallBack = nil;
        
        [self.locationManager stopUpdatingLocation];
    }
    
    [_locaitonTimer invalidate];
    _locaitonTimer = nil;
    _locationTime = 0;

}


- (void)doLocationAddressCallBackWithLocation:(NSArray *)result andResult:(NSError *)error
{
    if(_getLocationAddressCallBack){
        
        _getLocationAddressCallBack(result, error);
        _getLocationAddressCallBack = nil;
        
    }
    
    [_geoTimer invalidate];
    _geoTimer = nil;
    _geoTime = 0;
}

@end
